package com.eqdd.yiqidian.ui.mine.expense

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.http.HttpCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.kotlin.KotlinBaseActivity
import com.eqdd.yiqidian.kotlin.SingleChooseUtil
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.utils.HttpUtil
import com.eqdd.yiqidian.utils.PicUtil
import com.eqdd.yiqidian.utils.ToastUtil
import com.eqdd.yiqidian.widget.ActionSheetDialog
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_add_expense.*
import kotlinx.android.synthetic.main.list_item_122.view.*
import kotlinx.android.synthetic.main.list_item_124.view.*
import org.jetbrains.anko.forEachChild
import org.jetbrains.anko.forEachChildWithIndex
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.sdk25.coroutines.onLongClick
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast

/**
 * @author吕志豪 .
 * @date 18-3-22  上午9:06.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */
class AddExpenseActivity : KotlinBaseActivity() {

    companion object {
        val NAME = 99
        val MONEY = 100
        val SUBJECT = 101
        val BUDGET_AMOUNT = 103
        val BUDGET_SURPLUS = 104
        val BILL = 105
        val ANNEX = 106
        val INTRODUCE = 107
        val REMARK = 108
    }

    private var isOnly = true
    private var tvMoney: TextView? = null  //报销金额
    private var tvSubject: TextView? = null //报销类别
    private var tvBugdetAmount: TextView? = null // 预算金额
    private var tvBudgetSurplus: TextView? = null // 实际金额
    private var tvBill: TextView? = null //上传票据
    private var tvAnnext: TextView? = null //上传附件
    private var tvIntroduce: TextView? = null //费用说明

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_add_expense)
        super.onCreate(savedInstanceState)
        initTopBar("添加报销", "提交", View.OnClickListener {
            upLoad()
        })


        initView()


    }

    private fun initView() {
        val inflater: LayoutInflater = LayoutInflater.from(this)
        addView(inflater)

        //报销名称
        layout_name.onClick {
            val text = tv_name.text.toString()
            startActivityForResult<EditTextActivity>(NAME, "title" to "报销名称", "tip" to "报销名称", "content" to text)
        }


        //备注
        layout_remark.onClick {
            val text = tv_remark.text.toString()
            startActivityForResult<EditTextActivity>(REMARK, "title" to "备注", "tip" to "备注", "content" to text)
        }

        tv_add.onClick {
            addView(inflater)
        }


    }


    private fun addView(inflater: LayoutInflater) {

        val view = inflater.inflate(R.layout.list_item_122, null)
        //报销金额
        view.layout_money.onClick {
            val money = view.tv_money.text.toString()
            tvMoney = view.tv_money
            startActivityForResult<EditTextActivity>(MONEY, "title" to "报销金额",
                    "tip" to "报销金额", "content" to money, "onlyNumber" to true)
        }

        //报销科目
        view.layout_subject.onClick {
            var dialog: ActionSheetDialog
            SingleChooseUtil.getChooseDialog(this@AddExpenseActivity, 48,
                    object : SingleChooseUtil.OnGetDialog {
                        override fun onGetDialog(sheetDialog: ActionSheetDialog) {
                            dialog = sheetDialog
                            dialog.show()
                        }
                    },
                    object : SingleChooseUtil.OnSingChooseListener {
                        override fun onSingChooseListener(position: Int, strings: List<String>) {
                            view.tv_subject.text = strings[position - 1]
                        }
                    })

        }

        //是否有预算
        view.switch_btn.setOnCheckedChangeListener { v, isChecked ->
            if (isChecked) {
                view.layout_amount.visibility = View.VISIBLE
            } else {
                view.layout_amount.visibility = View.GONE
            }
        }

        //预算金额
        view.layout_budget_amount.onClick {
            val money = view.tv_budget_amount.text.toString()
            tvBugdetAmount = view.tv_budget_amount
            startActivityForResult<EditTextActivity>(BUDGET_AMOUNT, "title" to "预算金额",
                    "tip" to "预算金额", "context" to money, "onlyNumber" to true)
        }

        //剩余金额
        view.layout_budget_surplus.onClick {
            val money = view.tv_budget_surplus.text.toString()
            tvBudgetSurplus = view.tv_budget_surplus
            startActivityForResult<EditTextActivity>(BUDGET_SURPLUS, "title" to "剩余金额",
                    "tip" to "剩余金额", "context" to money, "onlyNumber" to true)
        }


        //费用说明
        view.layout_introduce.onClick {
            val money = view.tv_introduce.text.toString()
            tvIntroduce = view.tv_introduce
            startActivityForResult<EditTextActivity>(INTRODUCE, "title" to "费用说明", "tip" to "费用说明", "context" to money)
        }

        //图片
        view.iv_image.onClick {
            listview = view.listView
            PicUtil.single(this@AddExpenseActivity)
        }

        //删除
        view.tv_delete.onClick {
            layout_content.removeView(view)
            layout_content.forEachChildWithIndex { i, view ->
                view.tv_items.text = "报销明细" + (i + 1)
                if (layout_content.childCount == 1) {
                    view.tv_delete.visibility = View.GONE
                }
            }

        }


        //新增
        view.tv_items.text = "报销明细" + (layout_content.childCount + 1)
        if (layout_content.childCount == 0) {
            view.tv_delete.visibility = View.GONE
        } else if (isOnly) {
            layout_content.forEachChildWithIndex { i, view ->
                if (i == 0) {
                    view.tv_delete.visibility = View.VISIBLE
                }
            }
        }

        layout_content.addView(view)
    }


    private var listview: LinearLayout? = null


    private fun upLoad() {
        val list: ArrayList<ExpenseBean> = arrayListOf()
        var allMoney = 0.0
        layout_content.forEachChild {
            val bean = ExpenseBean()
            bean.billImage = arrayListOf()
            if (tv_name.text.isNullOrBlank()) {
                toast("请输入报销名称")
                return
            }
            if (it.tv_money.text.isNullOrBlank()) {
                toast("请输入报销金额")
                return
            }
            if (it.tv_subject.text.isNullOrBlank()) {
                toast("请输入报销科目")
                return
            }
            val money = it.tv_money.text.toString().toDouble()
            allMoney += money
            bean.money = money
            bean.reimburseType = it.tv_subject.text.toString()
            bean.isBudget = if (it.switch_btn.isClickable) 0 else 1
            bean.budgetMoney = if (it.tv_budget_amount.text.isNullOrBlank()) 0.0 else it.tv_budget_amount.text.toString().toDouble()
            bean.remainderMoney = if (it.tv_budget_surplus.text.isNullOrBlank()) 0.0 else it.tv_budget_surplus.text.toString().toDouble()
            bean.explain = it.tv_introduce.text.toString()
            it.listView.forEachChild {
                val media = it.tag as LocalMedia
                bean.billImage?.add(media.path)
            }
            list.add(bean)
        }
        val params = Gson().toJson(list)


        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.ADD_REIMBURSE)
                .params("userGuid", user?.guid.orEmpty())
                .params("reimbursetitle", tv_name.text.toString())
                .params("remarks", tv_remark.text.toString())
                .params("jsonPara", params)
                .params("companyId", user?.companyId ?: 0)
                .params("totalMoney", allMoney)
                .params("detailCount", layout_content.childCount)
                .execute(object : HttpCallBack<HttpResult<*>>(this@AddExpenseActivity) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val httpResult = response?.body()
                        ToastUtil.showShort(httpResult?.msg)
                        if (httpResult?.status == 200) {
                            setResult(Config.SUCCESS)
                            finish()
                        }
                    }

                    override fun onError(response: Response<HttpResult<*>>?) {
                        super.onError(response)
                    }
                })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.INTENT_CONTENT) {
            val content = data?.getStringExtra("content")
            when (requestCode) {
                NAME -> tv_name.text = content
                MONEY -> tvMoney?.text = content
                SUBJECT -> tvSubject?.text = content
                BUDGET_AMOUNT -> tvBugdetAmount?.text = content
                BUDGET_SURPLUS -> tvBudgetSurplus?.text = content
                BILL -> tvBill?.text = content
                ANNEX -> tvAnnext?.text = content
                INTRODUCE -> tvIntroduce?.text = content
                REMARK -> tv_remark.text = content
            }
        }
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            val inflater = LayoutInflater.from(this)
            val media = PictureSelector.obtainMultipleResult(data)[0]
            val view = inflater.inflate(R.layout.list_item_124, null)
            HttpUtil.upLoadPic(this, media.compressPath) { url -> media.path = url.substring(HttpConfig.BASE_URL.length - 1, url.length) }
            view?.tag = media
            Glide.with(this)
                    .load(media.compressPath)
                    .into(view.image)
            view.onClick {
                val mediaList: ArrayList<LocalMedia> = arrayListOf()
                (view.parent as LinearLayout).forEachChild {
                    mediaList.add(it.tag as LocalMedia)
                }
                PicUtil.preview(this@AddExpenseActivity, (view.parent as LinearLayout).indexOfChild(view), mediaList)
            }
            view.onLongClick {
                (view.parent as LinearLayout).forEachChild {
                    it.iv_delete.visibility = View.VISIBLE

                }
            }
            view.iv_delete.onClick {
                (view.parent as LinearLayout).removeView(view)
            }
            listview?.addView(view)
        }
    }


    class ExpenseBean {
        var money: Double? = 0.0
        var reimburseType: String = ""
        var isBudget: Int = 0
        var budgetMoney: Double? = 0.0
        var remainderMoney: Double? = 0.0
        var explain: String = ""
        var billImage: ArrayList<String>? = arrayListOf()
        var Enclosure: ArrayList<String>? = arrayListOf()
    }

}